export default {
  namespaced: true,
  state: () => ({
    cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
  }),
  mutations: {
    // 添加购物车
    addGoodsCart(state, goods) {
      const findResult = state.cart.find(x => x.goods_id == goods.goods_id)
      if(!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      this.commit('m_cart/saveStoryage')
    },
    
    // 保存购物车信息到本地
    saveStoryage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    
    // 切换购物车信息勾选状态
    cartCheckChange(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult) {
        findResult.goods_state = !goods.goods_state
        this.commit('m_cart/saveStoryage')
      }
    },
    
    // 保存购物车商品数量的更改
    updataGoodsCount(state, goods) {
      const findResult = state.cart.find(x => x.goods_id == goods.goods_id)
      if(findResult) {
        findResult.goods_count = goods.goods_count
        this.commit('m_cart/saveStoryage')
      }
    },
    
    // 删除商品
    removeCartGoods(state, goods) {
      state.cart = state.cart.filter(x => x.goods_id !== goods.goods_id)
      this.commit('m_cart/saveStoryage')
    },
    
    // 全选商品
    checkAll(state, radio) {
      state.cart.forEach(x => x.goods_state = radio)
      this.commit('m_cart/saveStoryage')
    }
  },
  getters: {
    // 统计购物车所有商品的和
    total(state) {
      // let c = 0
      // state.cart.forEach(x => c += x.goods_count)
      // return c
      return state.cart.reduce((num, item) => num += item.goods_count, 0)
    },
  
    // 统计所有选中的商品的数量
    fullCount(state) {
      return state.cart.filter(x => x.goods_state).reduce((total, count) => total += count.goods_count,0)
    },
    
    // 统计所有选中商品的价格
    checkedGoodsAmount(state) {
      return state.cart.filter(x => x.goods_state).reduce((count, item) => count += item.goods_count * item.goods_price, 0).toFixed(2)
    }
  }
}